package com.example.demo.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.example.demo.model.CaptchaProperties;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;
import java.util.Date;

@ResponseBody
@RequestMapping("/captcha")
@Controller
public class CaptchaController {
    //设置过期时间为60秒
    private final static long session_timeout = 60 * 1000;
    @Autowired
    private CaptchaProperties captchaProperties;

    @RequestMapping("/get")
    //从网页响应里面进行设置
    public void getCaptcha(HttpSession session, HttpServletResponse response){
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(200, 100);
        //将图片保存在网页中
        try {
            lineCaptcha.write(response.getOutputStream());
            //获取图片中的验证码，比对时就是用户输入的验证码和这个相比较
            lineCaptcha.getCode();
            //由于考虑到多线程的安全问题，所以这里使用用户一对一进行session存储
            session.setAttribute("captcha_session_key",lineCaptcha.getCode());
            session.setAttribute("captcha_session_date",new Date());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    @RequestMapping("/code")
    public Boolean check(String inputCode,HttpSession session){
        if (!StringUtils.hasLength(inputCode)){
            return false;
        }
        String savedCode = (String) session.getAttribute("captcha_session_key");
        Date surTime = (Date) session.getAttribute("captcha_session_date");
        //不区分大小写的字符串比较使用equalsIgnoreCase
        if (inputCode.equalsIgnoreCase(savedCode)){
            if (surTime != null && ((System.currentTimeMillis() - surTime.getTime()) < session_timeout)){
                return true;
            }
        }
        return false;
    }
}
